#!/bin/bash
#
# Utilities

export PYTHONPATH=../tnet/python
export PGI_BOUNDARY=__pgi_test_end__

die() {
  echo 1>&2 "$@"
  exit 1
}

unit() {
  "$@"
}

fly() {
  ./fly.py "$@"
}


# Utils

json2tnet() {
  ../tnet/python/tnet.py from-json "$@"
}


#
# Curl
#

curl() {
  fly run fly-state/curl -- "$@"
}

curl-test() {
  curl http://chubot.org/ "$@"
  echo "EXIT CODE: $?"
}

curl-bad() {
  fly run -v fly-state/curl -- BAD "$@"
  echo "EXIT CODE: $?"
}

# "Legacy" batch mode
curl-batch() {
  time ./curl_.py "http://wsgi.appspot.com/"
}

# Run in PGI mode without fly
curl-demo() {
  echo '{"argv": ["http://wsgi.appspot.com/"]}' \
    | json2tnet | PGI=1 ./curl_.py
}

# Run in PGI mode without fly
count-demo() {
  echo '{"argv": ["http://wsgi.appspot.com/"]}' \
    | json2tnet | PGI=1 ./count_.py
}

stop-curl() {
  fly stop -v fly-state/curl
}


#
# interleave
#

# Run without fly
interleave-demo() {
  echo '{"argv": ["10"]}' | json2tnet | PGI=1 ./interleave.py
}

interleave() {
  fly run -v fly-state/interleave 11 "$@"
}


#
# Show state
#

state() {
  fly state fly-state
}


#
# Errors
#

# TODO
# - First request is crash
# - 2 crashes in a row (need restart)
# - First request is good, second is crash (not working now)

#
# Process / Lock management
#



# This can be slow
lockinfo() {
  lsof | grep /mutex
}


listpgi() {
  ps aux | grep curl_ 
}

killpgi() {
  listpgi | row '$2' | xargs kill
}

# TODO: Print the process name too.  List command.
list() {
  local root="$1"
  test -n "$root" || die "Root required"
  find $root -name pid.txt | xargs cat
}

install() {
  local command=$1
  local dir=${2:-$command}
  test -n "$command" || "Command required"
  test -n "$dir" || "Dir required"

  mkdir fly-state
  mkdir fly-state/$dir
  touch fly-state/$dir/mutex

  pushd fly-state/$dir >/dev/null
  ln -s ../../$command command
  popd > /dev/null

  if which tree; then
    tree fly-state
  else
    find fly-state
  fi
}


#
# Perf test
#

# For just 100k.  Wow, big difference.
#
# fly$ ./do.sh chars
# 
# real    0m0.577s
# user    0m0.440s
# sys     0m0.180s
# 
# $ ./do.sh lines
# 
# real    0m0.070s
# user    0m0.100s
# sys     0m0.010s


chars() {
  time seq 100000 | ./misc/cat_demo.py char > /dev/null
}

lines() {
  time seq 100000 | ./misc/cat_demo.py line > /dev/null
}

#
# Docs
#

doc() {
  asciidoc -a toc fly.txt
  asciidoc -a toc README.txt
}


"$@"

